package com.kanq.util;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.Security;
import java.util.Base64;

public class SM4Util {
    private static final String ALGORITHM = "SM4/ECB/PKCS5Padding";
    private static final int KEY_SIZE = 128;

    /**
     * 生成SM4密钥
     *
     * @return Base64编码的密钥
     */
    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    public static String generateKey() throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("SM4", "BC");
        keyGenerator.init(KEY_SIZE);
        SecretKey secretKey = keyGenerator.generateKey();
        return Base64.getEncoder().encodeToString(secretKey.getEncoded());
    }

    /**
     * SM4加密方法
     *
     * @param plainText 明文
     * @param sm4Key    密钥
     * @return Base64编码的加密结果
     */
    public static String encrypt(String plainText, String sm4Key) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        byte[] keyBytes = Base64.getDecoder().decode(sm4Key);
        SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "SM4");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        byte[] encrypted = cipher.doFinal(plainText.getBytes());
        return Base64.getEncoder().encodeToString(encrypted);
    }

    /**
     * SM4解密方法
     *
     * @param encryptedData Base64编码的加密数据
     * @param sm4Key        密钥
     * @return 解密后的明文
     */
    public static String decrypt(String encryptedData, String sm4Key) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        byte[] keyBytes = Base64.getDecoder().decode(sm4Key);
        SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "SM4");
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
        return new String(decrypted);
    }

    public static void main(String[] args) throws Exception {
        String encrypted = encrypt("123", "4gXyFDJKWTJb+9eNvmBTGA==");
        System.out.println("加密结果：" + encrypted);
    }

}